package com.addzero.web.ui.components.drawer

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.addzero.web.ui.hooks.UseHook
import kotlin.math.roundToInt

/**
 * 通用抽屉组件 UseHook
 */
class UseGenericDrawer(
    /**
     *抽屉方向
     */
    val direction: DrawerDirection = DrawerDirection.FULLSCREEN,
    val title: String = "通用抽屉",
    val width: Int = 400,  // 宽度 (用于LEFT/RIGHT)
    val height: Int = 400, // 高度 (用于TOP/BOTTOM)
    val withBackdrop: Boolean = true,
    val content: @Composable () -> Unit
) : UseHook<UseGenericDrawer> {
    // 抽屉展开状态
    var isExpanded by mutableStateOf(false)

    // 抽屉位置偏移量
    var offset by mutableStateOf(0f)

    // 切换抽屉状态
    fun toggleDrawer() {
        isExpanded = !isExpanded
        // 重置偏移量
        offset = 0f
    }

    // 显示抽屉
    fun show() {
        isExpanded = true
        offset = 0f
    }

    // 隐藏抽屉
    fun hide() {
        isExpanded = false
        offset = 0f
    }

    override val render: @Composable () -> Unit = {
        val density = LocalDensity.current

        // 根据方向确定拖拽方向
        val dragOrientation = when (direction) {
            DrawerDirection.TOP, DrawerDirection.BOTTOM -> Orientation.Vertical
            DrawerDirection.LEFT, DrawerDirection.RIGHT -> Orientation.Horizontal
            DrawerDirection.FULLSCREEN -> Orientation.Vertical // 全屏模式使用垂直方向拖拽
        }

        // 拖拽状态
        val draggableState = rememberDraggableState { delta ->
            // 更新拖拽偏移量
            val newOffset = offset + delta
            val threshold = 300f

            // 根据方向限制拖拽范围
            when (direction) {
                DrawerDirection.TOP -> {
                    when {
                        isExpanded && newOffset < 0 -> offset = 0f
                        isExpanded && newOffset > threshold -> {
                            isExpanded = false
                            offset = 0f
                        }
                        !isExpanded && newOffset < -threshold -> {
                            isExpanded = true
                            offset = 0f
                        }
                        else -> offset = newOffset
                    }
                }
                DrawerDirection.BOTTOM -> {
                    when {
                        isExpanded && newOffset > 0 -> offset = 0f
                        isExpanded && newOffset < -threshold -> {
                            isExpanded = false
                            offset = 0f
                        }
                        !isExpanded && newOffset > threshold -> {
                            isExpanded = true
                            offset = 0f
                        }
                        else -> offset = newOffset
                    }
                }
                DrawerDirection.LEFT -> {
                    when {
                        isExpanded && newOffset < 0 -> offset = 0f
                        isExpanded && newOffset > threshold -> {
                            isExpanded = false
                            offset = 0f
                        }
                        !isExpanded && newOffset < -threshold -> {
                            isExpanded = true
                            offset = 0f
                        }
                        else -> offset = newOffset
                    }
                }
                DrawerDirection.RIGHT -> {
                    when {
                        isExpanded && newOffset > 0 -> offset = 0f
                        isExpanded && newOffset < -threshold -> {
                            isExpanded = false
                            offset = 0f
                        }
                        !isExpanded && newOffset > threshold -> {
                            isExpanded = true
                            offset = 0f
                        }
                        else -> offset = newOffset
                    }
                }
                DrawerDirection.FULLSCREEN -> {
                    when {
                        isExpanded && newOffset > 0 -> offset = 0f
                        isExpanded && newOffset < -threshold -> {
                            isExpanded = false
                            offset = 0f
                        }
                        !isExpanded && newOffset > threshold -> {
                            isExpanded = true
                            offset = 0f
                        }
                        else -> offset = newOffset
                    }
                }
            }
        }

        // 计算抽屉尺寸
        val drawerWidth = with(density) { width.dp }
        val drawerHeight = with(density) { height.dp }

        val drawerWidthPx = with(density) { drawerWidth.toPx() }
        val drawerHeightPx = with(density) { drawerHeight.toPx() }

        // 计算实际偏移量
        val actualOffset = when (direction) {
            DrawerDirection.TOP -> {
                if (isExpanded) {
                    IntOffset(0, offset.roundToInt())
                } else {
                    IntOffset(0, (-drawerHeightPx + 40f).roundToInt() + offset.roundToInt())
                }
            }
            DrawerDirection.BOTTOM -> {
                if (isExpanded) {
                    IntOffset(0, offset.roundToInt())
                } else {
                    IntOffset(0, (drawerHeightPx - 40f).roundToInt() + offset.roundToInt())
                }
            }
            DrawerDirection.LEFT -> {
                if (isExpanded) {
                    IntOffset(offset.roundToInt(), 0)
                } else {
                    IntOffset((-drawerWidthPx + 40f).roundToInt() + offset.roundToInt(), 0)
                }
            }
            DrawerDirection.RIGHT -> {
                if (isExpanded) {
                    IntOffset(offset.roundToInt(), 0)
                } else {
                    IntOffset((drawerWidthPx - 40f).roundToInt() + offset.roundToInt(), 0)
                }
            }
            DrawerDirection.FULLSCREEN -> {
                if (isExpanded) {
                    IntOffset(0, 0) // 全屏模式展开时无偏移
                } else {
                    IntOffset(0, drawerHeightPx.roundToInt()) // 全屏模式收起时移出屏幕
                }
            }
        }

        // 抽屉形状
        val shape = when (direction) {
            DrawerDirection.TOP -> RoundedCornerShape(bottomStart = 16.dp, bottomEnd = 16.dp)
            DrawerDirection.BOTTOM -> RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
            DrawerDirection.LEFT -> RoundedCornerShape(topEnd = 16.dp, bottomEnd = 16.dp)
            DrawerDirection.RIGHT -> RoundedCornerShape(topStart = 16.dp, bottomStart = 16.dp)
            DrawerDirection.FULLSCREEN -> RoundedCornerShape(0.dp) // 全屏模式无圆角
        }

        // 获取抽屉方向指示图标 - 箭头始终指向屏幕中央
        val directionIcon = when (direction) {
            DrawerDirection.TOP -> if (isExpanded) Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp
            DrawerDirection.BOTTOM -> if (isExpanded) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown
            DrawerDirection.LEFT -> if (isExpanded) Icons.AutoMirrored.Filled.KeyboardArrowRight else Icons.AutoMirrored.Filled.KeyboardArrowLeft
            DrawerDirection.RIGHT -> if (isExpanded) Icons.AutoMirrored.Filled.KeyboardArrowLeft else Icons.AutoMirrored.Filled.KeyboardArrowRight
            DrawerDirection.FULLSCREEN -> if (isExpanded) Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp // 全屏模式使用向下箭头表示收起
        }

        // 抽屉位置
        val drawerAlignment = when (direction) {
            DrawerDirection.TOP -> Alignment.TopCenter
            DrawerDirection.BOTTOM -> Alignment.BottomCenter
            DrawerDirection.LEFT -> Alignment.CenterStart
            DrawerDirection.RIGHT -> Alignment.CenterEnd
            DrawerDirection.FULLSCREEN -> Alignment.Center // 全屏模式居中显示
        }

        // 抽屉文字方向
        val isVertical = direction == DrawerDirection.LEFT || direction == DrawerDirection.RIGHT

        // 创建淡入淡出动画
        val backdropAlpha by animateFloatAsState(
            targetValue = if (isExpanded) 0.5f else 0f,
            animationSpec = tween(durationMillis = 300, easing = FastOutSlowInEasing)
        )

        Box(modifier = Modifier.fillMaxSize()) {
            // 背景遮罩
            if (withBackdrop && backdropAlpha > 0f) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .alpha(backdropAlpha)
                        .background(MaterialTheme.colorScheme.scrim)
                        .clickable(enabled = isExpanded) { hide() }
                )
            }

            // 上传抽屉
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = drawerAlignment
            ) {
                // 抽屉内容
                Box(
                    modifier = Modifier
                        .offset { actualOffset }
                        .let {
                            when (direction) {
                                DrawerDirection.TOP, DrawerDirection.BOTTOM ->
                                    it.fillMaxWidth().height(drawerHeight)
                                DrawerDirection.LEFT, DrawerDirection.RIGHT ->
                                    it.fillMaxHeight().width(drawerWidth)
                                DrawerDirection.FULLSCREEN ->
                                    it.fillMaxSize() // 全屏模式铺满整个屏幕
                            }
                        }
                        .clip(shape)
                        .background(MaterialTheme.colorScheme.surface)
                        .draggable(
                            state = draggableState,
                            orientation = dragOrientation
                        )
                ) {
                    // 抽屉内容
                    if (isVertical) {
                        // 水平抽屉（左/右）
                        Row(
                            modifier = Modifier.fillMaxSize()
                        ) {
                            // 拖拽手柄
                            Box(
                                modifier = Modifier
                                    .fillMaxHeight()
                                    .width(40.dp)
                                    .clickable { toggleDrawer() },
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.Center
                                ) {
                                    Icon(
                                        imageVector = directionIcon,
                                        contentDescription = if (isExpanded) "收起" else "展开",
                                        tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                                    )
                                    Spacer(modifier = Modifier.height(8.dp))
                                    if (title.isNotEmpty()) {
                                        Text(
                                            text = title,
                                            style = MaterialTheme.typography.titleMedium,
                                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f),
                                            modifier = Modifier.wrapContentWidth()
                                        )
                                    }
                                }
                            }

                            // 分隔线
                            Box(
                                modifier = Modifier
                                    .width(1.dp)
                                    .fillMaxHeight()
                                    .background(MaterialTheme.colorScheme.outlineVariant)
                            )

                            // 抽屉内容区域
                            if (isExpanded) {
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxHeight()
                                ) {
                                    content()
                                }
                            }
                        }
                    } else {
                        // 垂直抽屉（上/下）
                        Column(
                            modifier = Modifier.fillMaxSize()
                        ) {
                            // 拖拽手柄
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(40.dp)
                                    .clickable { toggleDrawer() },
                                contentAlignment = Alignment.Center
                            ) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.Center
                                ) {
                                    Icon(
                                        imageVector = directionIcon,
                                        contentDescription = if (isExpanded) "收起" else "展开",
                                        tint = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                                    )
                                    Spacer(modifier = Modifier.width(8.dp))
                                    if (title.isNotEmpty()) {
                                        Text(
                                            text = title,
                                            style = MaterialTheme.typography.titleMedium,
                                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)
                                        )
                                    }
                                }
                            }

                            // 分隔线 - 使用HorizontalDivider
                            HorizontalDivider()

                            // 抽屉内容区域
                            if (isExpanded) {
                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .fillMaxWidth()
                                ) {
                                    content()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/**
 * 通用抽屉组件
 */
@Composable
fun GenericDrawer(
    direction: DrawerDirection = DrawerDirection.RIGHT,
    title: String = "",
    width: Int = 400,
    height: Int = 400,
    withBackdrop: Boolean = true,
    content: @Composable () -> Unit
): UseGenericDrawer {

    val useGenericDrawer = UseGenericDrawer(
        direction = direction,
        title = title,
        width = width,
        height = height,
        withBackdrop = withBackdrop,
        content = content
    )
    useGenericDrawer.render{}
    return  useGenericDrawer
}
